package com.zlsy.thread.atomic;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicLong;

/**
 * @author zhouliang
 * @date 2020/8/12 19:27
 */
public class AtomicLongDemo {
    public static void main(String[] args) throws InterruptedException {
        AtomicLong atomic = new AtomicLong();
        CountDownLatch latch = new CountDownLatch(10000 * 10000);
        ExecutorService executorService = Executors.newFixedThreadPool(4);
        Task task = new Task(atomic, latch);
        long startTime = System.currentTimeMillis();
        for (int i = 0; i < 10000; i++) {
            executorService.execute(task);
        }
        latch.await();
        long endTime = System.currentTimeMillis();
        System.out.println(String.format("cost time:%s", endTime - startTime));
        executorService.shutdown();
    }
}

class Task implements Runnable {

    private AtomicLong atomic;
    private CountDownLatch latch;

    public Task(AtomicLong atomic, CountDownLatch latch) {
        this.atomic = atomic;
        this.latch = latch;
    }

    @Override
    public void run() {
        for (int i = 0; i < 10000; i++) {
            try {
                atomic.getAndIncrement();
            } finally {
                latch.countDown();
            }
        }
    }
}
